<?php

namespace app\index\controller;

use app\common\controller\HomeBase;
use app\common\model\Praise;
use app\common\model\User;
use app\common\model\Site as SiteMode;
use app\common\model\Tool;
use app\common\model\Ad;
use app\common\model\AdCategory;
use app\common\model\SiteCategory;
use app\common\model\News;
use app\common\model\UrlClickLog;
use app\common\model\FriendlyLink;
use think\Cache;

class Site extends HomeBase
{
    protected $siteConfig;
    protected $model;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new SiteMode();
        $this->siteConfig = Cache::get('site_config');
    }

    public function index()
    {
        $sites = $this->model->alias('a')
            ->join('site_category b', 'a.category_id=b.id', 'left')
            ->join('user c', 'a.user_id=c.id')
            ->where("a.status", 1)
            ->field('a.*,b.name,c.nickname')
            ->order('sort', 'desc')->paginate(10);
        $this->assign('sites', $sites);
        $this->assign('action', 'sites');
        return view();
    }

    public function detail($id)
    {
        $site = $this->model->alias('a')->join('site_category b', 'a.category_id=b.id', 'left')
            ->field('a.*,b.name')->where('a.status', 1)->where('a.id', $id)->find();
        if (!$site) {
            return $this->error('该站点不存在或暂时无权查看', 'index/site/index');
        }
        $site->total_view += 1;
        $site->month_view += 1;
        $site->save();
        $userInfo = (new User())->find($site->user_id);
        $this->assign('site', $site);
        $this->assign('user', $userInfo);
        $kinds = $this->model->where('category_id', $site->category_id)->orderRaw('rand()')->limit(8)->select();
        $this->assign('kinds', $kinds);
        $ip = '';
        if (session('userid')) {
            $map['user_id'] = session('userid');
        } else {
            $ip = $this->request->ip();
            $map['ip'] = $ip;
        }
        $isPraise = Praise::checkIsPraised(3, $id, session('userid'), $ip);
        $hasPraised = 0;
        if ($isPraise) {
            $hasPraised = 1;
        }
        //重新写hover
        $URI='/sites.html';
        $this->assign('URI', $URI);
        $this->assign('hasPraised', $hasPraised);
        $this->assign('action', 'site');
        return view();
    }
}
